<template>
    <div class="store-details">
        <div class="store-search">
            <el-form :model="searchContent" ref="searchFrom" :inline="true">
                <el-form-item label="集团" prop="depart_id">
                    <el-select 
                        v-model="searchContent.depart_id" 
                        placeholder="请选择集团"
                        @change="handleGroup">
                        <el-option
                            v-for="item in groupList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="store_id">
                    <el-select filterable v-model="searchContent.store_id" placeholder="请选择所属店铺">
                        <el-option
                            v-for="item in groupOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="月份">
                    <el-date-picker
                        v-model="searchContent.date"
                        type="month"
                        value-format="yyyy-M"
                        placeholder="选择月份"
                        :clearable="false"
                        :picker-options="pickerOptions"
                        @change="handleChangeMonth">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="地区" prop="area_id"> 
                    <el-cascader
                        v-model="searchContent.area_id"
                        :props="areaProps"
                        collapse-tags
                        placeholder="选择地区"
                        @change="handleChangeArea"
                        clearable>
                    </el-cascader>
                </el-form-item>
                <el-form-item label="品牌" prop="brand_id"> 
                    <el-cascader
                        v-model="searchContent.brand_id"
                        :props="brandsProps"
                        :options="brands"
                        placeholder="选择品牌"
                        :show-all-levels="false"
                        collapse-tags
                        @change="handleChangeBrand"
                        clearable>
                    </el-cascader>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button type="primary" @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="charts-main">
            <el-row :gutter="16">
                <el-col :span="8">
                    <History :dataArr="dataArr1"/>
                </el-col>
                <el-col :span="8">
                    <Grant :dataArr="dataArr2"/>
                </el-col>
                <el-col :span="8">
                    <CardUse :dataArr="dataArr3"/>
                </el-col>
            </el-row>
            <el-row :gutter="16">
                <el-col :span="8">
                    <Proportion :dataArr="dataArr4"/>
                </el-col>
                <el-col :span="16">
                    <Sales :dataArr="dataArr5"/>
                </el-col>
            </el-row>
            <el-row :gutter="16">
                <el-col :span="16">
                    <SalesProfit :dataArr="dataArr6"/>
                </el-col>
                <el-col :span="8">
                    <CostProfit :dataArr="dataArr7"/>
                </el-col>
            </el-row>
        </div>
    </div>
</template>
<script>
import { dateFormatter, formatterNumber } from '@/common/js/util'
import History from './history'
import Grant from './grant'
import CardUse from './card-use'
import Proportion from './proportion'
import Sales from './sales'
import SalesProfit from './sales-profit'
import CostProfit from './cost-profit'

export default {
    components: {
        History,
        Grant,
        CardUse,
        Proportion,
        Sales,
        SalesProfit,
        CostProfit
    },
    data() {
        const self = this;
        return {
            searchContent: {
                depart_id: null,      // 集团ID
                store_id: null,       // 集团外下属店铺ID 
                date: '',             // 日期
                area_id: 0,           // 城市ID   
                brand_id: 0,          // 经营品牌ID
                // is_search: true    // 是否处于搜索
            },
            groupList: [],            // 集团列表
            groupOptions: [],         // 店铺ID
            pageArr: {
                curpage: 1,           // 当前页码
                pageSize: localStorage.getItem('pageSize') * 1 || 10,         // 每页显示数量
                total: 0              // 数据总数
            },
            dataArr1: [],
            dataArr2: {
                series:  []
            },
            dataArr3: {
                series:  []
            },
            dataArr4: {
                series:  []
            },
            dataArr5: {
                series:  []
            },
            dataArr6: {
                series:  []
            },
            dataArr7: {
                series:  []
            },
            pickerMinDate: null,
            pickerOptions: {
                onPick: ({ maxDate, minDate }) => {
                    this.pickerMinDate = minDate
                },
                disabledDate: time => {
                    const diff = 248 // 仅支持最大选择248个月
                    const currDate1 = this.pickerMinDate ? new Date(this.pickerMinDate) : new Date()
                    const currDate2 = this.pickerMinDate ? new Date(this.pickerMinDate) : new Date()
                    const maxDate = new Date(currDate1.setMonth(currDate1.getMonth() + diff))
                    const minDate = new Date(currDate2.setMonth(currDate2.getMonth() - diff))
                    return Date.now() < time.getTime() || time.getTime() > maxDate.getTime() || time.getTime() < minDate.getTime()
                }
            },
            areaProps: {
                emitPath: false,
                lazy: true,
                lazyLoad(node, resolve) {
                    const { level } = node
                    if(level <= 1) {
                        self.getArea(node, resolve)
                    } else {
                        resolve()
                    }
                }
            },
            brandsProps: {
                // multiple: false,
                // checkStrictly: true,
                emitPath: false,
                // leaf: 'brand_leaf'
                lazy: true,
                lazyLoad(node, resolve) {
                    const { level } = node
                    if(level == 1) { // 品牌数据较多，首次禁止走懒加载，以防图表动画卡顿
                        self.getCarBrand(node, resolve)
                    } else {
                        resolve(self.brands)
                    }
                }
            },
            brands: []
        }
    },
    methods: {
        handleGroup(depart_id = null) {
            if (depart_id !== null) {
                this.groupOptions = []
                this.searchContent.store_id = null
            }
            if (depart_id === 0) return
            this.$http.post('/crm/coupons/index.php?act=statistics&op=getCouponDepart', { depart_id })
            .then(res => {
                if (res.data) {
                    if (!depart_id) {
                        this.groupList = [
                            { label: '全部', value: 0 },
                            ...res.data.map(item => ({ 
                                label: item.depart_name, 
                                value: parseInt(item.depart_id) 
                            }))
                        ]
                    } else {
                        this.groupOptions = [
                            ...res.data.map(item => ({ label: item.depart_name, value: item.store_id }))
                        ]
                    }
                }
            }).catch(error => {
                error && this.$message.error(`${error}`)
            })
        },
        getArea(node, resolve) {
            const fid = node.value || 0
            this.$http.post('/admin/store/index.php?act=getArea&op=selectArea', {fid}).then(res => {
                const nodes = res.map(item => ({
                    value: item.area_id,
                    label: item.area_name,
                    leaf: node.level >= 1
                }))
                resolve(nodes)
            })
        },
        getCarBrand(node, resolve) {
            const fid = node && node.value || 1
            this.$http.post('/admin/store/index.php?act=getBrand&op=selectBrand', {fid}).then(res => {
                if(!node) {
                    this.brands = res.map(item => ({
                        value: item.brand_id,
                        label: item.brand_initial + ' ' + item.brand_name
                    }))
                } else {
                    let disabled = {}
                    if(node.level == 0) disabled = { disabled: true }
                    const nodes = res.map(item => ({
                        value: item.brand_id,
                        label: item.brand_initial + ' ' + item.brand_name,
                        // ...disabled,
                        //brand_leaf: node.level >= 1,
                        leaf: node.level >= 1
                    }))
                    resolve(nodes)
                }
            })
        },
        handleChangeMonth(val) {
            this.searchContent.date = val;
        },
        handleChangeArea(val) {
            this.searchContent.area_id = val;
        },
        handleChangeBrand(val) {
            this.searchContent.brand_id = val
        },
        handleSearch() {
            // if(!this.searchContent.is_search) this.searchContent.is_search = true;
            this.pageArr.curpage = 1;
            this.getData();
        },
        handleReset() {
            this.$refs.searchFrom.resetFields();
            this.searchContent.date = dateFormatter("YYYY-M")
            this.pageArr.curpage = 1
            this.getData()
        },
        getData() {
            let datas = {
                pageSize: this.pageArr.pageSize,
                page: this.pageArr.curpage
            }
            //if(this.searchContent.is_search) {
                datas = {
                    ...datas,
                    ...this.searchContent
                }
            //}
            this.$http.post("/crm/coupons/index.php?act=statistics&op=getCouponStatisticsNew", datas)
            .then(res => {
                // console.log(res)
                if(res.code == 1) {
                    let { statistics_list, statistics_info } = res.data
                    statistics_info = statistics_info ? statistics_info : []
                    statistics_info.reverse()

                    // 历史数据概况
                    this.dataArr1 = [
                        statistics_list[0].grant || 0,
                        statistics_list[0].surplusCost || 0,
                        statistics_list[0].salesVolume || 0,
                        statistics_list[0].verify || 0,
                        statistics_list[0].surplusValue || 0,
                        statistics_list[0].salesDeduction || 0
                    ]

                    // 卡券发放数
                    const dataArr2 = statistics_info.map(item => ([parseInt(item.addTime) * 1000, parseFloat(item.grant)]));
                    const total2 = dataArr2.reduce((sum, item) => {
                        return sum + item[1];
                    }, 0) || 0;
                    const average2 = dataArr2.length > 0 ? Math.round(total2 / dataArr2.length) : 0
                    this.dataArr2 = {
                        title: {
                            text: `<span class="highcharts-title-span">月均发放卡券张数: ${formatterNumber(average2, 100000, 2, true)}张</span>`
                        },
                        series: [{
                            name: '发放',
                            color: '#1890FF',
		                    data: dataArr2.length > 0 && dataArr2 || this.defaultValue(),
                        }]
                    }

                    // 卡券核销数
                    const dataArr3 = statistics_info.map(item => ([parseInt(item.addTime) * 1000, parseFloat(item.verify)]));
                    const total3 = dataArr3.reduce((sum, item) => {
                        return sum + item[1];
                    }, 0) || 0;
                    const average3 = dataArr3.length > 0 ? Math.round(total3 / dataArr3.length) : 0
                    this.dataArr3 = {
                        title: {
                            text: `<span class="highcharts-title-span">月均核销卡券张数: ${formatterNumber(average3, 100000, 2, true)}张</span>`
                        },
                        series: [{
                            name: '核销',
                            borderRadius: 2,
                            linecolor: '#FE9291',
                            color: {
                                linearGradient: {x1: 0, x2: 0, y1: 0, y2: 1},
                                stops: [
                                    [0, '#F4DB42'],
                                    [1, '#FE9291'],
                                    // [2, 'rgb(254, 146, 145, 0.3)']
                                ],
                            },
		                    data: dataArr3.length > 0 && dataArr3 || this.defaultValue(),
                        }]
                    }
                    
                    // 发放核销比
                    let [
                        verify, 
                        grant, 
                        expired, 
                        invalid, 
                        valid = grant - verify - expired - invalid
                    ] = [
                        this.numberValidate(statistics_list[0].verify),  // 不存在则初始化0.001，否则图表插件报错
                        this.numberValidate(statistics_list[0].grant, 0.004),
                        this.numberValidate(statistics_list[0].expired),
                        this.numberValidate(statistics_list[0].invalid)
                    ]
                    const verify_percentage = Math.ceil(verify.toFixed(2) * 10000 / grant) / 100
                    if(verify + grant + expired + invalid > 1) { // 说明当中存在不为0 或者 undefined 的值
                        verify = verify == 0.001 ? 0 : verify
                        expired = expired == 0.001 ? 0 : expired
                        invalid = invalid == 0.001 ? 0 : invalid
                        valid = valid == 0.001 ? 0 : valid
                    } 
                    this.dataArr4 = {
                        verify_percentage,
                        series: [{
                            data: [{
                                name: '核销',
                                y: verify,
                                z: 110
                            },{
                                name: '未使用',
                                y: valid < 0 ? 0 : valid,
                                z: 150
                            },{
                                name: '过期',
                                y: expired,
                                z: 190
                            },{
                                name: '失效',
                                y: invalid,
                                z: 230
                            }]
                        }]
                    };

                    // 卡券销售
                    const dataArr5 = [
                        statistics_info.map(item => ([parseInt(item.addTime) * 1000, parseFloat(item.salesVolume)])),
                        statistics_info.map(item => ([parseInt(item.addTime) * 1000, parseFloat(item.salesCost)]))
                    ]
                    this.dataArr5.series = [
                        {
                            name: '卡券销售金额',
                            borderRadius: 2,
                            linecolor: '#4293F4',
                            color: {
                                linearGradient: {x1: 0, x2: 0, y1: 0, y2: 1},
                                stops: [
                                    [0, '#4293F4'],
                                    [1, 'rgb(66, 147, 244, 0.3)']
                                ],
                            },
                            pointPlacement: 0.04,
                            data: dataArr5[0].length > 0 && dataArr5[0] || this.defaultValue()
                        }, {
                            name: '已售卡券成本',
                            borderRadius: 2,
                            linecolor: '#68F5E2',
                            color: {
                                linearGradient: {x1: 0, x2: 0, y1: 0, y2: 1},
                                stops: [
                                    [0, '#68F5E2'],
                                    [1, 'rgb(104, 245, 226, 0.3)']
                                ],
                            },
                            pointPlacement: -0.04,
                            data: dataArr5[1].length > 0 && dataArr5[1] || this.defaultValue()
                        }
                    ]

                    // 销售利润
                    const dataArr6 = statistics_info.map(item => ([parseInt(item.addTime) * 1000, parseFloat(item.salesProfit)]))
                    const total6 = dataArr6.reduce((sum, item) => {
                        return sum + item[1];
                    }, 0) || 0;
                    const average6 = dataArr6.length > 0 ? Math.round(total6 / dataArr6.length) : 0
                    this.dataArr6 = {
                        title: {
                            text: `<span class="highcharts-title-span">月均利润: ${formatterNumber(average6, 100000, 2, true)}元</span>`
                        },
                        series: [{
                            name: '利润',
                            color: '#FF5A5A',
		                    data: dataArr6.length > 0 && dataArr6 || this.defaultValue(),
                        }]
                    }

                    // 成本利润
                    let [
                        salesProfit, 
                        salesCost, 
                        profit_percentage = salesCost > 0.001 ? (salesProfit * 100 / salesCost).toFixed(2) : 0
                    ] = [
                        this.numberValidate(statistics_list[0].salesProfit),
                        this.numberValidate(statistics_list[0].salesCost)
                    ]
                    this.dataArr7 = {
                        profit_percentage,
                        series: [{
                            data: [
                                ["利润", salesProfit],
                                ['成本', salesCost]
                            ],
                        }]
                    }
                }
            })
        },
        numberValidate(num, value = 0.001) {
            num = parseFloat(num)
            if(!num || num == 0) {
                num = value
            }
            return num;
        },
        defaultValue() {
            const date = new Date(this.searchContent.date)
            const val = [
                [date.getTime(), 0]
            ]
            for(let i = 0; i < 5; i++) {
                date.setMonth(date.getMonth() - 1)
                val.push([date.getTime(), 0])
            }
            return val.reverse()
        }
    },
    created() {
        this.searchContent.date = dateFormatter("YYYY-M")
        this.searchContent.depart_id = 600
        this.handleGroup() // 获取集团列表
        this.handleGroup(600) // 获取集团对应店铺数据
        this.getCarBrand(null, null)
        this.getData()
    },
    mounted() {
        // 清除 el-main 的内边距
        const elMain = document.querySelector(".el-main")
        if (elMain) elMain.style.padding = '0px'
    },
    destroyed() {
        const elMain = document.querySelector(".el-main")
        if (elMain) elMain.style.padding = ''
    }
}
</script>
<style lang="scss" scoped>
    .store-details {
        background: #f6f6f6;
        color: #fff;
        width: 100%;
        height: 100%;
        padding: 16px;
        display: flex;
        align-items: space-between;
        flex-direction: column;
        justify-content: flex-start;
    }
    .store-search {
        /deep/.el-date-editor .el-range-separator {
            width: 8%;
        }
        /deep/.el-form-item__label {
            padding-right: 8px;
        }
    }
    .charts-main {
        flex-flow: 1;
        height: 100%;
        display: flex;
        align-items: space-between;
        flex-direction: column;
        justify-content: space-between;
        .el-row {
            height: calc(33.33333333333% - 10px);
            .el-col { height: 100%; }
        }
        .chart-box {
            width: 100%;
            height: 100%;
            background: #ffffff;
            box-shadow: 0px 1px 5px #e9e9e9;
            border-radius: 2px;
        }
        /deep/.chart-title {
            font-weight: bold;
            font-size: 14px;
            padding: 10px 18px;
            display: block;
            position: relative;
            overflow: hidden;
            border-bottom: 1px solid #f3f3f3;
            color: #555;
            .icon {
                width: 1.2em;
                height: 1.2em;
                vertical-align: -0.18em;
            }
        }
        /deep/.chart-content {
            height: calc(100% - 42px);
            overflow: hidden;
            font-size: 14px;
        }
    }
</style>